<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 再分配客户 </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button v-if="threeLevelsbool.huiHai" :loading="haiFlg" type="primary" class="handle-del mr10" @click="handleSetPublic">放入公海</el-button>
        <template>
          <el-button v-if="threeLevelsbool.chuExcel" type="primary" class="handle-del mr10" :loading="exceltrueFlg" @click="exceltrue"
                     style="float: left; margin-right: 10px">导出excel</el-button>
          <el-button v-else type="primary" class="handle-del mr10" :loading="excelfalseFlg" @click="excelfalse"
                     style="float: left; margin-right: 10px">导出excel</el-button>
        </template>
        <el-date-picker class="mr10" v-model="startTime_endTime" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
        <el-input v-model="query.kw" placeholder="请输入用户名/电话查询" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </div>
      <el-table v-loading="loading" :data="tableData" border class="table" style="width: 100%" ref="multipleTable"
                header-cell-class-name="table-header" @selection-change="handleSelectionChange" @filter-change="levelChange"
                @sort-change="sortChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" :index="tableIndex" label="序号" width="55" align="center"></el-table-column>
        <el-table-column width="55" label="标记" align="center">
          <template slot-scope="scope">
            <div>
              <i class="el-icon-star-on" v-loading="scope.row.biaoFlg" element-loading-spinner="el-icon-loading"
                 :class="scope.row.cIsFlag === '0' ? '' : 'IconColor'" @click="signClick(scope.row)"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="cName" label="客户名称" width="120">
          <template slot-scope="scope">
            <el-link v-if="threeLevelsbool.edit" type="primary" :underline="false" @click="drawerStateClick(scope.row.cId, scope.row.cIsFlag)">
              {{ scope.row.cName }}
            </el-link>
            <el-link v-else type="primary" :underline="false">
              {{ scope.row.cName }}
            </el-link>
            <span v-if="threeLevelsbool.edit && win.tccc" class="tccctel" @click="tcccClick(scope.row.cId, scope.row.cIsFlag)"><i
                 class="el-icon-phone-outline"></i>云</span>
          </template>
        </el-table-column>
        <el-table-column label="电话" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.cPhone }}</span>
            <i v-if="threeLevelsbool.edit" class="el-icon-phone" :style="{'fontSize':'20px','color':'#409EFF','cursor':'pointer'}"
               @click="clickTel(scope.row.cId, scope.row.cIsFlag)"></i>
          </template>
        </el-table-column>
        <el-table-column label="客户级别" width="120" column-key="jibie"
                         :filters="[{text:'A(重要客户)',value:'A'},{text:'B(优质客户)',value:'B'},{text:'C(普通客户)',value:'C'}]" filter-placement="bottom-end"
                         :filter-method="filterTag">
          <template slot-scope="scope">{{
                        scope.row.cLevel === 'A' ? 'A(重要客户)' : scope.row.cLevel === 'B' ? 'B(优质客户)' : 'C(普通客户)'
                    }}</template>
        </el-table-column>
        <el-table-column prop="newFollowUpRecord" label="最新跟进记录" width="180"></el-table-column>
        <el-table-column prop="fromName" label="客户来源" width="120"></el-table-column>
        <el-table-column prop="fromSeasName" label="所属公海" width="120"></el-table-column>
        <el-table-column prop="cCreateTime" label="创建时间" width="200" sortable="custom"></el-table-column>
        <el-table-column prop="newFollowUpTime" label="最新跟进时间" width="200" sortable="custom"></el-table-column>
        <el-table-column label="成交状态" align="center" fixed="right" width="150">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.cStatus === '0'">待跟进</el-tag>
            <el-tag v-if="scope.row.cStatus === '2'">已跟进/在考虑</el-tag>
            <el-tag v-if="scope.row.cStatus === '3'">已邀约/待上门</el-tag>
            <el-tag v-if="scope.row.cStatus === '4'">已沟通/不需要</el-tag>
            <el-tag v-if="scope.row.cStatus === '5'">已上门/待签约</el-tag>
            <el-tag v-if="scope.row.cStatus === '6'">已上门/资质不符</el-tag>
            <el-tag v-if="scope.row.cStatus === '1'" type="success">已成交</el-tag>
            <el-tag v-if="scope.row.cStatus === '7'" type="warning">已签约</el-tag>
            <el-tag v-if="scope.row.cStatus === '8'" type="warning">已进件</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="签单操作" width="100" align="center">
          <template slot-scope="scope">
            <p style="margin-bottom:5px;"><el-button type="primary" size="mini" icon="el-icon-edit" @click="followClick(scope.row,7)"
                         :disabled="scope.row.cStatus == 8 || scope.row.cStatus == 1">签约</el-button>
            </p>
            <p style="margin-bottom:5px;"><el-button type="warning" size="mini" icon="el-icon-edit" @click="followClick(scope.row,8)"
                         :disabled="scope.row.cStatus == 1">进件</el-button>
            </p>
            <p><el-button type="success" size="mini" icon="el-icon-edit" @click="followClick(scope.row,1)">成交</el-button></p>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button v-if="threeLevelsbool.remove" type="text" icon="el-icon-delete" class="red" @click="removeList(scope.row.cId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total,sizes, prev, pager, next" :current-page="query.page" :page-size="query.limit"
                       :page-sizes="[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]" :total="totalCount" :pager-count="5"
                       @size-change="handlePageSelectChange" @current-change="handlePageChange" @prev-click="handlePageChange"
                       @next-click="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 查看客户信息窗口 -->
    <customer-model ref="drawerState" @fathergetData="getData"></customer-model>
    <!-- 跟进状态修改 -->
    <followUp ref="followUp"></followUp>
  </div>
</template>

<script>
import {
  RedistributionTableAjax,
  customerSetPublicAjax,
  customerSetFlagAjax,
  RolePermissionsQX,
  ExcelZha,
  ExcelChu,
  customerFormRemove,
  customerTel
} from '../../../api/index';
import customermodel from '../../common/customermodel';
import followUp from '../../common/followUp.vue';
export default {
  data() {
    return {
      win: window,
      loading: true,
      startTime_endTime: [],
      query: {
        page: 1,
        limit: 10,
        startTime: '',
        endTime: '',
        kw: '',
        //筛选
        leavels: [],
        orderbyfollowup: 0,
        orderbycreate: 0,
        orderdo: '',
      },
      totalCount: 0,
      totalPage: 0,

      tableData: [],
      multipleSelection: [],

      haiFlg: false,

      threeLevelsbool: {
        edit: false,
        remove: false,
        huiHai: false,
        chuExcel: false
      },

      excelfalseFlg: false,
      exceltrueFlg: false
    };
  },
  components: {
    'customer-model': customermodel,
    'followUp': followUp,
  },
  created() {
    this.getData();
    this.threeLevels();
  },
  watch: {
    $route: 'getData'
  },
  methods: {
    // 获取 easy-mock 的模拟数据
    getData() {
      this.loading = true;
      if (typeof (this.query.leavels) == 'object') {
        this.query.leavels = this.query.leavels.length > 0 ? this.query.leavels.join(',') : '';
      }
      RedistributionTableAjax(this.query).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          res.recordList.forEach(item => {
            item.biaoFlg = false;
          })
          this.tableData = res.recordList;
          this.totalCount = res.totalCount;
          this.totalPage = res.totalPage;
        } else {
          this.$message(res.msg);
        }
      });
    },
    //放入公海
    handleSetPublic() {
      if (this.multipleSelection.length > 0) {
        this.haiFlg = true;
        customerSetPublicAjax({ cIds: this.multipleSelection }).then((res) => {
          this.haiFlg = false;
          if (res.code === 0) {
            this.$message.success('放入成功');
            this.multipleSelection = [];
            this.getData();
          } else {
            this.$message(res.msg);
          }
        });
      } else {
        this.$message('请选择放入客户');
      }
    },
    //序号
    tableIndex(index) {
      return (this.query.page - 1) * this.query.limit + index + 1;
    },
    //标记客户
    signClick(item) {
      let id = item.cId;
      item.biaoFlg = true;
      customerSetFlagAjax({ cId: id }).then((res) => {
        item.biaoFlg = false;
        if (res.code === 0) {
          if (item.cIsFlag === '1') {
            item.cIsFlag = '0';
            this.$message.success('取消成功');
          } else {
            item.cIsFlag = '1';
            this.$message.success('标记成功');
          }
        } else {
          this.$message(res.msg);
        }
      });
    },
    // 分页切换
    handlePageChange(val) {
      this.loading = true;
      this.$set(this.query, 'page', val);
      this.getData();
    },
    // 分页调整
    handlePageSelectChange(val) {
      this.loading = true;
      this.$set(this.query, 'limit', val);
      this.getData();
    },
    //列表客户等级筛选
    filterTag(value, row, column) {
      return true;
    },
    //筛选时间监听
    levelChange(filters) {
      console.log(filters);
      this.query.leavels = filters.jibie ? filters.jibie : [];
      this.getData();
    },
    //列表时间日期排序
    sortChange(item) {
      console.log(item);
      if (item.prop == 'newFollowUpTime') {
        this.query.orderdo = 2;
        this.query.orderbyfollowup = item.order == 'ascending' ? 1 : item.order == 'descending' ? 2 : 0;
      }
      if (item.prop == 'cCreateTime') {
        this.query.orderdo = 1;
        this.query.orderbycreate = item.order == 'ascending' ? 1 : item.order == 'descending' ? 2 : 0;
      }
      this.getData();
    },
    //搜索
    handleSearch() {
      this.query.page = 1;
      if (this.startTime_endTime) {
        this.query.startTime = this.startTime_endTime[0];
        this.query.endTime = this.startTime_endTime[1];
      } else {
        this.query.startTime = '';
        this.query.endTime = '';
      }
      this.getData();
    },
    //删除客户
    removeList(id) {
      this.$confirm('确定删除当前客户吗？', '删除客户', {
        type: 'warning'
      })
        .then(() => {
          this.loading = true;
          customerFormRemove({ cusId: id }).then((res) => {
            if (res.code === 0) {
              this.$message.success("删除成功");
              this.getData();
            } else {
              this.$message(res.msg);
            }
          });
        })
        .catch(() => { });
    },
    //点击查看客户信息
    drawerStateClick(id, flag, tccc) {
      this.$refs.drawerState.drawerStateClick(id, flag, tccc);
    },
    // 多选操作
    handleSelectionChange(val) {
      let arr = [];
      val.forEach((item, i) => {
        arr.push(item.cId);
      });
      this.multipleSelection = arr;
    },
    //点击导出（假）
    excelfalse() {
      if (this.multipleSelection.length > 0) {
        this.excelfalseFlg = true;
        ExcelZha({ cusIds: this.multipleSelection }).then((res) => {
          this.excelfalseFlg = false;
          if (res.code === 0) {
            this.$message('导出失败，请联系管理员');
          } else {
            // this.$message(res.msg);
          }
        });
      } else {
        this.$message('请选择要导出的数据');
      }
    },
    //点击导出（真）
    exceltrue() {
      if (this.multipleSelection.length > 0) {
        this.$confirm('导出过程中请不要刷新或者离开页面', '提示', {
          type: 'warning'
        }).then(() => {
          this.exceltrueFlg = true;
          ExcelChu({ cusIds: this.multipleSelection }).then((res) => {
            this.exceltrueFlg = false;
            const link = document.createElement('a');
            let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
            link.download = '客户信息';
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            this.$message.success('导出成功');
          });
        });
      } else {
        this.$message('请选择要导出的数据');
      }
    },
    //三级权限
    threeLevels() {
      let parentRouth = this.$route.path.replace('/', '');
      RolePermissionsQX({ urlName: parentRouth }).then((res) => {
        if (res.code === 0) {
          res.buttons.forEach((item, i) => {
            switch (item.name) {
              case '编辑':
                this.threeLevelsbool.edit = item.pageIsShow;
                break;
              case '删除':
                this.threeLevelsbool.remove = item.pageIsShow;
                break;
              case '放入公海':
                this.threeLevelsbool.huiHai = item.pageIsShow;
                break;
              case '导出':
                this.threeLevelsbool.chuExcel = item.pageIsShow;
                break;
            }
          });
        } else {
          this.$message(res.msg);
        }
      });
    },
    //点击拨号
    clickTel(id, flg) {
      this.drawerStateClick(id, flg);
      customerTel({ cusId: id }).then(res => {
        if (res.code == 0) {
          this.$message.success("开始拨号");
        } else {
          this.$message(res.msg);
        }
      })
    },
    //点击云呼叫
    tcccClick(id, flg) {
      if (!window.tccc) {
        this.$message("暂未开通云呼功能，请联系管理员");
        return;
      }
      this.drawerStateClick(id, flg, 'tccc');
    },
    //修改跟进状态
    followClick(item, num) {
      this.$refs.followUp.getInit({ id: item.cId, tel: item.cPhone, name: item.cName, type: num });
    }
  }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.el-icon-star-on >>> .el-loading-spinner {
    margin-top: -10px;
}
.IconColor {
    color: #e6a23c;
}
/deep/ :focus {
    outline: 0;
}
.el-drawer__title {
    color: #72767b;
    -webkit-box-align: center;
    align-items: center;
    margin-bottom: 25px;
    padding: 20px 35px 0;
}
.el-drawer__title span {
    font-size: 14px;
    color: #66b1ff;
    margin: 20px;
    cursor: pointer;
}
.el-radio {
    margin-right: 0px;
}
.beizhu_text {
    height: 794px;
    overflow: auto;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    margin-left: 35px;
    padding: 20px;
    box-sizing: border-box;
    color: #72767b;
    font-size: 14px;
}
.beizhu_text > div:first-child {
    padding-top: 0;
}
.beizhu_text > div {
    padding: 5px 0;
}
.el-icon-star-on {
    font-size: 20px;
}
</style>
